﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.BRL;
using BYFW.DAL;
using System.Data;
using LDSP.Util;
using LDSP.Helper;
using System.IO;
using System.Drawing;
using System.Text;

namespace LDSP.UI.EnterpriseAdmin
{
    public partial class MngTaskPlan : BRL.BaseEnterprisePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitialControls();
                this.InitData();
                this.GetCondition();
                this.BindGrid();
            }
        }

        #region Column indexes
        private int col_chb = 0;
        private int col_index = 1;
        private int col_subdiary_name = 2;
        private int col_taskName = 3;
        private int col_status = 4;
        private int col_person = 5;
        private int col_expiredDT = 6;
        private int col_progress = 7;
        private int col_type = 8;
        private int col_changeDT = 9;
        #endregion

        #region Colors
        //到期未完成 ---------淡蓝色
        //已完成  --------淡绿色
        //未开始  ----------淡红色
        //进行中  ----淡黄色
        private Color Color_InProgress = Color.Gold;
        private Color Color_Finished = Color.PaleGreen;
        private Color Color_Paused = Color.SkyBlue;
        private Color Color_Expired_UnFinished = Color.Pink;
        private Color Color_Label_ForColor = Color.White;

        #endregion

        protected bool IsEnterpriseGroupAdmin
        {
            get
            {
                return this.LoginUser != null && this.LoginUser.Enterprise != null && this.LoginUser.Enterprise.IsEnterpriseGroup == true;
            }
        }

        protected void InitData()
        {
            //不缓存则清空页面信息
            if (!needCachePageInfo)
            {
                g_pageInfo.ClearPageInfo();
            }
            this.SetSpecialPageInfo();
            this.BindDDLPageSize();
        }

        /// <summary>
        /// 传入参数，设置过滤条件
        /// </summary>
        protected void SetSpecialPageInfo()
        {
            g_pageInfo.Direction = true;
            g_pageInfo.Sort = "name";
            g_pageInfo.PageSize = GetPageSizeSetting();
            g_pageInfo.PageIndex = this.grd_list.PageIndex;
        }

        private void InitialControls()
        {
            BindDDLStatus();
            BindDDLSubdiary();

            this.lbl_task_all.BackColor = Color.FromArgb(121, 154, 225);
            this.lbl_expired_unfinished.BackColor = Color_Expired_UnFinished;// Color.MistyRose;
            this.lbl_task_inProgress.BackColor = Color_InProgress;// Color.LightYellow;
            this.lbl_task_completed.BackColor = Color_Finished;// Color.PaleGreen;
            this.lbl_task_paused.BackColor = Color_Paused;// Color.LightBlue;

            this.lbl_task_all.ForeColor = Color_Label_ForColor;
            this.lbl_expired_unfinished.ForeColor = Color_Label_ForColor;
            this.lbl_task_inProgress.ForeColor = Color_Label_ForColor;
            this.lbl_task_completed.ForeColor = Color_Label_ForColor;
            this.lbl_task_paused.ForeColor = Color_Label_ForColor;

            this.tr_subdiary.Visible = IsEnterpriseGroupAdmin;
            this.grd_list.Columns[col_subdiary_name].Visible = IsEnterpriseGroupAdmin;

            //显示正确的表格头
            UIHelper.SyncGridHeadColumn(grd_list, grd_list_head);
        }

        private void BindDDLStatus()
        {
            this.ddl_status.Items.Clear();
            this.ddl_status.Items.Add(new ListItem("所有", "0"));
            this.ddl_status.Items.Add(new ListItem("到期未完成", "4"));
            this.ddl_status.Items.Add(new ListItem("进行中", "00"));
            this.ddl_status.Items.Add(new ListItem("已完成", "1"));
            this.ddl_status.Items.Add(new ListItem("暂停", "3"));
            try
            {
                this.ddl_status.SelectedIndex = 0;
            }
            catch { }
        }
        protected void BindDDLSubdiary()
        {
            List<Enterprise> subdiaryList = this.LoginUser.Enterprise.GetSubsidiaryList();

            this.ddl_subdiary.Items.Clear();
            this.ddl_subdiary.Items.Add(new ListItem("--请选择子公司--", "0"));

            foreach (Enterprise sub in subdiaryList)
            {
                this.ddl_subdiary.Items.Add(new ListItem(sub.Code, sub.ID.ToString()));
            }
            try
            {
                this.ddl_subdiary.SelectedIndex = 0;
            }
            catch { }
        }
        protected void BindDDLPageSize()
        {
            CommonControlInitial.InitialPageSize(this.ddl_pageSize);
            this.ddl_pageSize.SelectedValue = g_pageInfo.PageSize.ToString();
        }
        protected void BindGrid()
        {
            DataTable dt = null;
            if (IsEnterpriseGroupAdmin)
            {
                dt = BYFW.SFL.CommonOP.SortedTable(new Plan().GetRecords(g_pageInfo.ConditionWhere), g_pageInfo.GetSortExpression());
            }
            else if (this.LoginUser.UserType == EnterpriseUserType.企业管理员)
            {
                dt = BYFW.SFL.CommonOP.SortedTable(new Plan().GetRecordsByEnterprise(this.LoginUser.EnterpriseID, g_pageInfo.ConditionWhere), g_pageInfo.GetSortExpression());
            }
            else if (this.LoginUser.UserType == EnterpriseUserType.普通用户)
            {
                dt = BYFW.SFL.CommonOP.SortedTable(new Plan().GetRecordsByEnterpriseAndUser(this.LoginUser.EnterpriseID, this.LoginUser.ID, g_pageInfo.ConditionWhere), g_pageInfo.GetSortExpression());
            }

            this.grd_list.PageSize = g_pageInfo.PageSize;
            this.grd_list.PageIndex = g_pageInfo.PageIndex;
            this.grd_list.DataSource = dt;
            this.grd_list.DataBind();

            SavePageSizeSetting();
            this.TotalRecords.Text = LDSP.Helper.StringUtil.GetSearchText(dt.Rows.Count);

            this.SetStatusNumber(dt);

            //绑定空的表格头
            UIHelper.BindEmptyHeader(grd_list_head, dt);
        }

        protected void GetCondition()
        {
            string cond = "";

            if (!string.IsNullOrEmpty(this.txt_cod_name.Text))
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLMultiCondition("docName", EDataType.String, this.txt_cod_name.Text.Trim(), true, true), true);
            }

            if (!string.IsNullOrEmpty(this.txt_referenceNumber.Text))
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLMultiCondition("department", EDataType.String, this.txt_referenceNumber.Text, true, true), true);
            }

            if (!string.IsNullOrEmpty(this.txt_implementStartDT.Text))
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("expiredDT", EDataType.Date, this.txt_implementStartDT.Text, ">=", true), true);
            }

            if (!string.IsNullOrEmpty(this.txt_implementEndDT.Text))
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("expiredDT", EDataType.Date, this.txt_implementEndDT.Text, "<=", true), true);
            }

            if (!string.IsNullOrEmpty(this.txt_name.Text))
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLMultiCondition("name", EDataType.String, this.txt_name.Text, true, true), true);
            }

            if (!string.IsNullOrEmpty(this.txt_principle.Text))
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLMultiCondition("person", EDataType.String, this.txt_principle.Text, true, true), true);
            }

            if (this.ddl_status.SelectedIndex >= 1)
            {
                //到期未完成
                if (this.ddl_status.SelectedValue == "4")
                {//状态不是完成，即"1".
                    cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("status", EDataType.Int, "1", "<>", true), true);

                    //过期时间小于今天.
                    cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("expiredDT", EDataType.Date, DateTime.Now.ToShortDateString(), "<", true), true);
                }
                else
                {
                    cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("status", EDataType.Int, this.ddl_status.SelectedValue, "=", true), true);
                }
            }

            if (IsEnterpriseGroupAdmin)
            {
                //将favoriteID作为查询集合
                IEnumerable<R_EnterpriseCodification> enterpriseCods = new List<R_EnterpriseCodification>();

                //得到所有子公司的集合
                if (this.ddl_subdiary.SelectedIndex == 0)
                {
                    IList<Enterprise> enterprises = this.LoginUser.Enterprise.GetSubsidiaryList();
                    foreach (Enterprise enterprise in enterprises)
                    {
                        enterpriseCods = enterpriseCods.Concat<R_EnterpriseCodification>(
                            new R_EnterpriseCodification().GetListByEnterprise(enterprise.ID));
                    }
                }
                else
                {
                    enterpriseCods = new R_EnterpriseCodification().GetListByEnterprise(Int32.Parse(this.ddl_subdiary.SelectedValue));
                }

                StringBuilder favorateIdBuilder = new StringBuilder();
                foreach (R_EnterpriseCodification r_ec in enterpriseCods)
                {
                    favorateIdBuilder.Append(r_ec.ID.ToString() + ";");
                }

                //防止空数据
                if (favorateIdBuilder.Length == 0)
                {
                    favorateIdBuilder.Append("-1");
                }

                cond = this.AppendCondition(cond, DefaultDB.GetSQLInAndNotInCondition("favoriteID", EDataType.Int, favorateIdBuilder.ToString(), true, false), true);
            }

            g_pageInfo.Condition = cond;
        }

        /// <summary>
        /// 根据数据源，设置每个状态的数量显示
        /// </summary>
        /// <param name="dt"></param>
        protected void SetStatusNumber(DataTable dt)
        {
            this.lbl_task_all.Text = "任务总数：" + dt.Rows.Count;

            int expired_unfinished = 0;
            int inProgress = 0;
            int completed = 0;
            int paused = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Plan ett = new Plan();
                ett.GetProperties(dt.Rows[i]);
                switch ((TaskStatus)ett.Status)
                {
                    case TaskStatus.暂停:
                        paused++;
                        break;
                    case TaskStatus.进行中:
                        inProgress++;
                        break;
                    case TaskStatus.已完成:
                        completed++;
                        break;
                }

                if (ett.ExpiredDT.Date < DateTime.Now.Date && ett.Status != (int)TaskStatus.已完成)
                {
                    expired_unfinished++;
                }
            }

            this.lbl_expired_unfinished.Text = "到期未完成：" + expired_unfinished;
            this.lbl_task_inProgress.Text = "进行中：" + inProgress;
            this.lbl_task_completed.Text = "已完成：" + completed;
            this.lbl_task_paused.Text = "暂停：" + paused;
        }

        protected void btn_search_Click(object sender, EventArgs e)
        {
            this.GetCondition();
            this.BindGrid();
        }

        protected void grd_list_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int id = this.GetInt(e.CommandArgument.ToString());
                if (e.CommandName == "deleteItem")
                {
                    Plan ett = new Plan();
                    ett.GetProperties(id);
                    ett.Delete();
                }
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Plan ett = new Plan();
                    ett.GetProperties(((DataRowView)e.Row.DataItem).Row);
                    this.ShowSequenceNumber(e.Row, col_index);

                    //设置翻页的checkbox选中
                    CheckBox chb = (CheckBox)e.Row.FindControl("chb");
                    chb.Attributes["docid"] = ett.ID.ToString();
                    if (this.MultiPageIncludeCheckedId(this.hid_docIDs, ett.ID))
                    {
                        chb.Checked = true;
                    }

                    WebControl c = (WebControl)e.Row.FindControl("lnk_update");
                    if (IsEnterpriseGroupAdmin)
                    {
                        this.JSShowModalDialog("pid=" + ett.ID, c);
                    }
                    else
                    {
                        R_EnterpriseCodification r_eg = new R_EnterpriseCodification().GetEnterpriseCodificationByID(ett.FavoriteID);
                        this.JSShowModalDialog("pid=" + ett.ID + "&enterpriseid=" + r_eg.EnterpriseID, c);
                    }

                    //粗体显示未查看任务
                    R_User_ViewPlan uvp = new R_User_ViewPlan().GetByUserAndPlan(this.LoginUser.ID, ett.ID);
                    if (uvp == null || uvp.ViewDT < ett.ChangeDT)
                    {
                        e.Row.Font.Bold = true;
                    }

                    e.Row.Cells[col_subdiary_name].Text = ett.EnterpriseCodification.Enterprise.Code;
                    e.Row.Cells[col_expiredDT].Text = this.FormatDT(ett.ExpiredDT);
                    e.Row.Cells[col_changeDT].Text = this.FormatDT(ett.ChangeDT);
                    e.Row.Cells[col_status].Text = ((TaskStatus)ett.Status).ToString();
                    e.Row.Cells[col_progress].Text = ett.Progress.Replace("\n", "</br>");
                    e.Row.Cells[col_type].Text = ((TaskPlanType)(ett.Type)).ToString();

                    UIHelper.AppendEmptyLine(e.Row, col_taskName, col_progress);

                    string principleStr = GetPrincipleListStr(new R_PlanPrinciple().GetListByPlan(ett.ID));
                    if (!string.IsNullOrEmpty(principleStr))
                    {
                        e.Row.Cells[col_person].Text = principleStr;
                    }

                    //更新颜色，
                    if (ett.ExpiredDT.Date < DateTime.Now.Date && (TaskStatus)ett.Status != TaskStatus.已完成)
                    {
                        e.Row.BackColor = Color.MistyRose;
                    }
                    else
                    {
                        switch ((TaskStatus)ett.Status)
                        {
                            case TaskStatus.暂停:
                                e.Row.BackColor = Color.LightBlue;
                                break;
                            case TaskStatus.进行中:
                                e.Row.BackColor = Color.LightYellow;
                                break;
                            case TaskStatus.已完成:
                                e.Row.BackColor = Color.PaleGreen;
                                break;
                        }
                    }

                    e.Row.ToolTip = StringUtil.TaskPlanTitle(ett);
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                g_pageInfo.PageIndex = e.NewPageIndex;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (g_pageInfo.Sort == e.SortExpression)
                {
                    g_pageInfo.Direction = !g_pageInfo.Direction;
                }
                else
                {
                    g_pageInfo.Direction = true;
                }
                g_pageInfo.Sort = e.SortExpression;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void ddl_pageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                g_pageInfo.PageSize = this.GetInt(this.ddl_pageSize.SelectedValue);
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        private void JSShowModalDialog(string arg, WebControl ctrl)
        {
            this.JSShowDialog("AddTaskPlan.aspx?" + arg, 1200, 500, ctrl, null, null, null, null, null, null, null, true, null, null, null, null, null);
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            //获取模板
            string file = Server.MapPath("..\\..\\..\\Templates\\UserSpecified\\Plan\\" + this.LoginUser.EnterpriseID + ".xls");
            string template = !string.IsNullOrEmpty(this.LoginUser.Enterprise.EnterpriseConfig.TaskPlanTemplateName) ? file : Server.MapPath("..\\..\\..\\Templates\\TaskPlan.xls");

            this.GetCondition();

            DataTable dt = null;
            if (IsEnterpriseGroupAdmin)
            {
                dt = BYFW.SFL.CommonOP.SortedTable(new Plan().GetRecords(g_pageInfo.ConditionWhere), g_pageInfo.GetSortExpression());
            }
            else if (this.LoginUser.UserType == EnterpriseUserType.企业管理员)
            {
                dt = BYFW.SFL.CommonOP.SortedTable(new Plan().GetRecordsByEnterprise(this.LoginUser.EnterpriseID, g_pageInfo.ConditionWhere), g_pageInfo.GetSortExpression());
            }
            else if (this.LoginUser.UserType == EnterpriseUserType.普通用户)
            {
                dt = BYFW.SFL.CommonOP.SortedTable(new Plan().GetRecordsByEnterpriseAndUser(this.LoginUser.EnterpriseID, this.LoginUser.ID, g_pageInfo.ConditionWhere), g_pageInfo.GetSortExpression());
            }

            new TaskPlanExport().Export(this.Server, dt, template);
        }

        protected void btnExportSelected_Click(object sender, EventArgs e)
        {
            string file = Server.MapPath("..\\..\\..\\Templates\\UserSpecified\\Plan\\" + this.LoginUser.EnterpriseID + ".xls");
            string template = !string.IsNullOrEmpty(this.LoginUser.Enterprise.EnterpriseConfig.TaskPlanTemplateName) ? file : Server.MapPath("..\\..\\..\\Templates\\TaskPlan.xls");

            //Collect task plans.
            IDictionary<string, IList<Plan>> codifications = new Dictionary<string, IList<Plan>>();
            GridView grid = this.grd_list;
            List<int> ids = this.GetAllCheckedItems(this.hid_docIDs);

            if (ids.Count > 0)
            {
                DataTable dt = new Plan().GetRecordByID(ids[0]).Table;
                dt.Rows.Clear();
                for (int i = 0; i < ids.Count; i++)
                {
                    DataRow ett = new Plan().GetRecordByID(ids[i]);
                    dt.Rows.Add(ett.ItemArray);
                }
                new TaskPlanExport().Export(this.Server, dt, template);
            }
            else
            {
                this.JSAlert("请选择要导出的任务计划!");
            }
        }
    }
}